package org.visionlibrary.image.filters.rescaling;

import java.awt.image.ColorModel;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Level extends AbstractFilter {
	protected int oldl = 256;
	protected int newl = 128;
	protected double factor = 0;
	protected int[] lut;

	public Level() {
		this(256, 128, 0);
	}
	
	public Level(int oldLevel, int newLevel, double factor) {
		this.oldl = oldLevel;
		this.newl = newLevel;
		this.factor = factor;
	}

	@Override
	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		int maxX = src.getWidth();
		int maxY = src.getHeight();
		for (int ch = 0; ch < src.getNumBands(); ch++) {
			ColorModel cm = src.getColorModel();
			int componentSize = cm.getComponentSize(ch);
			int length = (int) Math.pow(2, componentSize);

			lut = new int[length];

			for (int i = 0; i < lut.length; i++)
				lut[i] = (int) ((((double) i / (double) oldl) + factor) * (double) newl);

			for (int x = 0; x < maxX; x++)
				for (int y = 0; y < maxY; y++) {
					int pixel = src.getSample(x, y, ch);
					dest.setSample(x, y, ch, lut[pixel]);
				}
		}

		return dest;
	}
}
